<template>
  <div class="readskill">
    <loading v-if="!skillData._id" />
    <div v-else class="skill-wrapper">
      <div class="user">
        <user-info :userInfo="skillData.user[0]" @sendMessage="_sendMessage"></user-info>

        <div class="user-article-class" v-if="skillCol.length">
          <div class="label">技术文章分类</div>
          <ul class="slide-item">
            <li v-for="(data,index) in skillCol" :key="data._id">
              <div class="title">
                <h4>{{data.name}}</h4>
                <span>
                  文章数：
                  <i>{{data.skillNumber}}</i>
                </span>
              </div>
              <p class="desc" v-if="data.desc">{{data.desc}}</p>
              <div
                class="tags"
                v-if="data.tags.length || (data.tags.length === 1 && !data.tags[0])"
              >
                <el-tag size="small" v-for="tag in data.tags" :key="tag.id" v-if="tag">
                  <span>{{tag}}</span>
                </el-tag>
              </div>
              <div class="time">
                <span>更新日期：{{data.updated | setDate}}</span>
                <div
                  v-if="data.children.length"
                  class="add-more"
                  :class="classIndex === index ? 'active' : ''"
                  @click="openChildSkillData(index)"
                >
                  <span>V</span>
                  <span>V</span>
                </div>
              </div>
              <div
                class="class-child-skill"
                :style="{height: classIndex === index ? 30 * data.children.length + 20 + 'px' : '0'}"
              >
                <ul>
                  <li
                    v-for="childrenData in data.children"
                    @click="gotoThisSkill(childrenData._id)"
                    :key="childrenData._id"
                  >
                    <span>{{childrenData.label}}</span>
                    <i>{{childrenData.type}}</i>
                  </li>
                </ul>
              </div>
            </li>
          </ul>
        </div>
        <bei></bei>
      </div>
      <div class="article">
        <div class="article-content">
          <div class="label">
            <div class="title">
              <h1>
                <span>{{skillData.label}}</span>
              </h1>
              <div class="number">
                <span>
                  <i class="el-icon-view"></i>
                  <i>{{skillData.watch + skillWatchNum}}</i>
                </span>
                <el-badge :value="skillData.skillId | skillStarFilters(star)" class="badge">
                  <el-button size="mini" @click="skillStar(skillData.skillId)">赞</el-button>
                </el-badge>
              </div>
            </div>
            <div class="hot">
              <span v-if="skillData.type">文章类型：{{skillData.type}}</span>
              <span v-if="skillData.name">技术文章分类：{{skillData.name}}</span>
              <span v-if="skillData.hot">标记热门：{{skillData.hot === true ? "是" : "否"}}</span>
            </div>
            <div class="intro">
              <span class="name" v-if="skillData.user[0].name">{{skillData.user[0].name}}</span>
              <span v-if="skillData.created">发布于：{{skillData.created | setDate}}</span>
              <span v-if="skillData.updated">更新日期：{{skillData.updated | setDate}}</span>
              <span v-if="skillData.readNumber">阅读数：{{skillData.readNumber}}</span>
              <span v-if="skillData.commentNumber">评论数：{{skillData.commentNumber}}</span>
            </div>
          </div>
          <div class="body-wrapper">
            <div class="body marked" v-html="markedMethods(skillData.body)"></div>
          </div>
        </div>
        <div class="send-message">
          <div v-if="userInfoData && userName" class="has-loging">
            <div class="user-cover">
              <img :src="userInfoData.coverUrl | squareUrls" alt />
            </div>
            <div class="textarea">
              <el-input
                v-model="skillCommentData"
                type="textarea"
                :placeholder="userInfoData.name ? userInfoData.name + '：你想对这篇文章说些什么？' : userName + '你想对这篇文章说些什么？'"
              ></el-input>
            </div>
            <div class="btn">
              <el-button type="small" @click="sendSkillCommentData()">发送</el-button>
            </div>
          </div>
          <div v-else class="no-log">
            <span>你还未登录，只有登录之后才能对这篇文章提交评论！</span>
          </div>
        </div>
        <div class="comment-area" v-if="skillCommentDatas.length">
          <single-comment
            :userInfoData="userInfoData"
            :userName="userName"
            :skillCommentDatas="skillCommentDatas"
            @_updateSkillCommentData="_updateSkillCommentData"
            @_commentStar="_commentStar"
            :star="star"
            :skillData="skillData"
          ></single-comment>
        </div>
        <recommend :recommendData="recommendData" />
      </div>
    </div>
  </div>
</template>

<script>
import marked from "marked";
import { slider } from "@/public/slider.js";
import recommend from "@/components/comment/recommend";
import userInfo from "@/components/comment/userInfo.vue";
import { mapState, mapActions, mapMutations } from "Vuex";
import singleComment from "@/views/readskill/singleComment";
export default {
  name: "readskill",
  components: {
    "single-comment": singleComment,
    "user-info": userInfo,
    recommend
  },
  data() {
    return {
      skillData: {},
      skillCol: [],
      skillCommentData: "",
      classIndex: -1,
      star: [],
      limit: 10,
      skip: 0,
      recommendData: "",
      skillWatchNum: 0
    };
  },
  filters: {
    skillStarFilters(id, star) {
      if (star.length) {
        let newData = [];
        for (let i = 0; i < star.length; i++) {
          if (!star[i].commentId) {
            if (star[i].id === id) {
              newData.push(star[i]);
            }
          }
        }
        // 执行了2到3次。没找到问题在哪里。
        return newData.length;
      } else {
        return 0;
      }
    }
  },
  activated() {
    this.skillData = {};
    let _id = this.$route.params.id;
    this.setSkillWatchData({ _id }).then(res => {
      this.initMethods();
    });
  },
  watch: {
    $route(now, pre) {
      if (now.name === "article_id" && pre.name === "article_id") {
        this.skillData = {};
        let _id = this.$route.params.id;
        this.setSkillWatchData({ _id }).then(res => {
          this.initMethods();
        });
      }
    }
  },
  methods: {
    _commentStar(data) {
      let ip = returnCitySN.cip;
      this.setStar({
        id: this.skillData.skillId,
        ip,
        commentId: data.commentId
      })
        .then(res => {
          this._getSkillStar();
          alert(res.data.data);
        })
        .catch(err => {
          console.log(err);
        });
    },
    skillStar(id) {
      let ip = returnCitySN.cip;
      this.setStar({
        id,
        ip,
        parentFlog: true
      })
        .then(res => {
          this._getSkillStar();
          alert(res.data.data);
        })
        .catch(err => {
          console.log(err);
        });
    },
    initMethods() {
      // 初始化方法
      let _id = this.$route.params.id;

      this.getSkillInId({
        _id
      }).then(res => {
        this.skillData = res.data.data;
        this._getSkillStar();
        this.getSkillCommentData({
          id: this.skillData._id
        });
        this.getAllSkillCol(this.skillData.user[0].userName).then(res => {
          this.skillCol = res.data.data;
          this.$nextTick(() => {
            slider(
              document
                .getElementsByClassName("readskill")[0]
                .getElementsByClassName("slide-item")[0]
            );
          });
        });
        this.getRecommendSkill({
          limit: this.limit,
          skip: this.skip,
          userName: this.skillData.user[0].userName
        })
          .then(res => {
            this.recommendData = res.data.data;
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    _getSkillStar() {
      this.getSkillStar({ id: this.skillData.skillId })
        .then(res => {
          this.star = res.data.data;
        })
        .catch(err => {
          console.log("错误提示：" + err);
        });
    },
    openChildSkillData(index) {
      //展开分类的子节点，并且展示出数据
      this.classIndex = index;
    },
    gotoThisSkill(_id) {
      this.$router.push("/article/" + _id);
    },
    _updateSkillCommentData() {
      this.getSkillCommentData({
        id: this.skillData._id
      });
    },
    sendSkillCommentData() {
      let data = this.skillCommentData;
      if (data) {
        let collection = {
          id: this.skillData._id,
          userName: this.skillData.user[0].userName,
          commentData: this.skillCommentData,
          sendUserName: this.userInfoData.userName || this.userName,
          sendUserCoverUrl: this.userInfoData.coverUrl || "",
          skillId: this.skillData.skillId
        };

        this.setSkillCommentData(collection)
          .then(res => {
            if (res.data.ok === 1) {
              this.getSkillCommentData({
                id: this.skillData._id
              });
              this.skillCommentData = "";
              alert(res.data.data);
            } else {
              console.log(res.data.data);
            }
          })
          .catch(err => {
            console.log("错误信息：" + err);
          });

        // 给文章作者发送留言
        if (this.userName) {
          this.sendMessageToUser({
            text: data,
            sendUserName: this.userInfoData.userName || this.userName,
            userName: this.skillData.user[0].userName,
            sendCoverUrl: this.userInfoData.coverUrl || "",
            system: true,
            id: this.skillData._id,
            label: this.skillData.label,
            type: this.$route.path.split("/")[1]
          })
            .then(res => {
              console.log("ok");
            })
            .catch(err => {
              console.log("错误信息：" + err);
            });
        } else {
          alert("你还未登录，无法给作者留言！");
        }
      } else {
        alert("你没有输入任何文字！");
      }
    },
    _sendMessage() {
      // 给文章作者发送留言
      if (this.userName) {
        this.$prompt("请输入要发送的内容", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        })
          .then(({ value }) => {
            if (value) {
              this.sendMessageToUser({
                text: value,
                sendUserName: this.userInfoData.userName || this.userName,
                userName: this.skillData.user[0].userName,
                sendCoverUrl: this.userInfoData.coverUrl || ""
              })
                .then(res => {
                  this.$alert(res.data.data);
                })
                .catch(err => {
                  console.log("错误信息：" + err);
                });
            } else {
              alert("检测内容为空，未提交数据！");
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        alert("你还未登录，无法给作者留言！");
      }
    },
    markedMethods(data) {
      return marked(data);
    },
    // _setSkillData() {
    //   let allSkillData = this.allSkillData;
    //   let _id = this.$route.params.id;
    //   for (let i = 0; i < allSkillData.length; i++) {
    //     if (allSkillData[i]._id === _id) {
    //       this.skillData = allSkillData[i];

    //       this._getSkillStar();
    //       this.getSkillCommentData({
    //         id: this.skillData._id
    //       });
    //       this.getAllSkillCol(this.skillData.user[0].userName).then(res => {
    //         this.skillCol = res.data.data;
    //       });
    //       this.getRecommendSkill({
    //         limit: this.limit,
    //         skip: this.skip,
    //         userName: this.skillData.user[0].userName
    //       })
    //         .then(res => {
    //           this.recommendData = res.data.data;
    //         })
    //         .catch(err => {
    //           console.log(err);
    //         });

    //       return;
    //     }
    //   }
    // },

    ...mapActions("user", [
      "getAllSkillCol",
      "sendMessageToUser",
      "setSkillCommentData",
      "getSkillCommentData",
      "getSkillInId",
      "setStar",
      "getSkillStar",
      "getRecommendSkill",
      "setSkillWatchData"
    ])
    // ...mapMutations("user", ["setAllSkillData"])
  },
  computed: {
    ...mapState("user", [
      // "allSkillData",
      "userInfoData",
      "userName",
      "skillCommentDatas"
    ])
  }
};
</script>

<style lang="sass" scoped>
@import '@/assets/default.sass'
@keyframes addMore1
  0%
    top: 15px
  20%
    top: 20px
  100%
    top: 20px
@keyframes addMore2
  0%
    top: 10px
  20%
    top: 15px
  100%
    top: 15px
.readskill
  width: 100%
  height: 100%
  background-color: #eee
  padding: 20px 0
  min-height: 93vh
  .skill-wrapper
    width: 1280px
    height: 100%
    margin: 0 auto
    @include flex(space-between,flex-start)
    .user
      flex: 0 0 25%
      overflow: hidden    
      .user-article-class
        width: 100%
        background-color: #fff
        margin-top: 10px
        .label
          width: 100%
          height: 40px
          line-height: 40px
          font-size: 16px
          color: #333
          font-weight: 700
          position: relative
          padding-left: 10px
          border-bottom: 1px solid #eee
          &:before
            content: ""
            width: 5px
            height: 18px
            background-color: #eb2001
            position: absolute
            left: 0
            top: 11px
        >ul
          padding: 20px
          width: 100%
          overflow: hidden
          >li
            width: 100%
            padding: 5px 0
            border-bottom: 1px solid #f9f9f9
            .class-child-skill
              width: 100%
              height: 0
              overflow: hidden
              transition: height .5s
              >ul
                width: 100%
                color: #999
                padding: 10px 20px
                overflow: hidden
                background-color: #eee
                >li
                  border-bottom: 1px solid #fff
                  line-height: 30px
                  height: 30px
                  overflow: hidden
                  cursor: pointer
                  @include flex(space-between,center)
                  >span
                    flex: 1
                    overflow: hidden
                    text-overflow: ellipsis
                    white-space: nowrap
                  >i
                    flex: 0 0 20%
                    text-align: right
                    overflow: hidden
                    text-overflow: ellipsis
                    white-space: nowrap
                  &:last-child
                    border: none
            .title
              width: 100%
              height: 30px
              line-height: 30px
              @include flex(space-between,flex-start)
              >h4
                margin-right: 20px
                font-size: 16px
                flex: 0 0 60%
                overflow: hidden
                text-overflow: ellipsis
                white-space: nowrap
              >span
                color: #666
                >i
                  color: #eb2001
            .time
              line-height: 30px
              height: 30px
              width: 100%
              overflow: hidden
              position: relative
              >span
                width: 100%
                display: block
                overflow: hidden
                text-overflow: ellipsis
                white-space: nowrap
              .add-more
                position: absolute
                right: 5px
                top: -18px
                width: 40px
                height: 40px
                color: #2eb037
                cursor: pointer
                >span:first-child
                  position: absolute
                  left: 15px
                  top: 15px
                  animation: addMore1 5s ease 4s infinite
                >span:last-child
                  position: absolute
                  left: 15px
                  top: 20px
                  animation: addMore2 5s ease 4s infinite  
              .active
                >span
                  transition: .3s
                  transform: rotate(180deg)
            .desc
              width: 100%
              line-height: 25px
              overflow: hidden
              display: -webkit-box
              -webkit-box-orient: vertical
              -webkit-line-clamp: 2
            .tags
              width: 100%
              height: 24px
              overflow: hidden
              @include flex(flex-start,center)
              @include align(flex-start)
              .el-tag
                flex: 0 0 19%
                margin: 0 0.5%
                overflow: hidden
                text-overflow: hidden
                white-space: nowrap
                @include flex(center,center) 
            &:last-child
              border: none
    .article
      flex: 0 0 74%
      overflow: hidden
      .article-content
        background-color: #fff
        padding: 20px
        .label
          width: 100%
          border-bottom: 1px solid #eee
          .title
            width: 100%
            height: 40px
            @include flex(space-between,center)
            >h1
              flex: 1
              color: #333
            .number
              flex: 0 0 20%
              @include flex(space-between,center)
              >span
                font-size: 18px
                >i
                  margin-right: 5px
          .intro
            width: 100%
            height: 30px
            line-height: 30px
            @include flex(space-between,center)
            >span
              display: block
            .name
              color: #0487dc          
          .hot
            width: 100%
            height: 40px
            line-height: 40px
            @include flex(space-between,center)
            >span
              display: block
        .body-wrapper
            padding: 30px 0
            overflow: hidden
      .send-message
        margin-top: 10px
        width: 100%
        background-color: #fff
        padding: 20px
        .has-loging
          width: 100%
          padding: 20px 0
          @include flex(space-between,center)
          .user-cover
            flex: 0 0 32px
            height: 32px
            overflow: hidden
            border-radius: 5px
            @include flex(center,center)
            >img
              width: 100%
              height: auto
          .textarea
            flex: 1
            padding: 0 2%
        .no-log
          width: 100%
          height: 134px
          @include flex(center,center)
      .comment-area
        width: 100%
        margin-top: 10px
        background-color: #fff
        padding: 20px
</style>